﻿using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace test
{

    public class Baidu_Accurate
    {
        // 百度AI识别图片
        public static string SBZP(string photoAddress, string apitoken)
        {
            string token = apitoken;
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=" + token;
            Encoding encoding = Encoding.Default;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = getFileBase64(photoAddress);
            String str = "image=" + HttpUtility.UrlEncode(base64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string result = reader.ReadToEnd();
            //通用文字识别（高精度含位置版）;
            return result;
        }

        //图片转 Base64 
        public static String getFileBase64(String fileName, string baseHead = "")
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baseHead + baser64;
        }

        private static string token = "";
        private static DateTime tokenTime = DateTime.MinValue;

        public static string GetToken(string AppId, string Secret)
        {
            if (tokenTime < DateTime.Now)
            {
                var resultInfo = Ss(AppId, Secret);
                JObject jObject = JObject.Parse(resultInfo);
                token = jObject["access_token"] + "";
                if (token == null)
                {
                    return "";
                }
                
                tokenTime = DateTime.Now.AddDays(10);
            }
            return token;
        }

        private static string Ss(string AppId, string Secret)
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={AppId}&client_secret={Secret}");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            IRestResponse response = client.Execute(request);
            return response.Content;
        }
    }


    public class ORCResult
    {
        public List<Word> words_result { get; set; }
        public string words_result_num { get; set; }
        public string log_id { get; set; }
    }

    public class Word
    {
        public string words { get; set; }
        public Location location { get; set; }
    }
    public class Location
    {
        public int top { get; set; }
        public int left { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }
}
